package com.rc.saas.mini.minip.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.rc.saas.mini.common.base.TResponse;
import com.rc.saas.mini.common.constant.HttpConstant;
import com.rc.saas.mini.common.constant.SessionConstants;
import com.rc.saas.mini.minip.token.RedisTokenLoader;
import com.rc.saas.mini.model.tenant.Tenant;
import com.rc.saas.mini.service.tenant.TenantService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * （没用到）
 * 运营商拦截器
 * Created by sven on 2018-02-16 13:29
 */
public class MemberInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = LogManager.getLogger(MemberInterceptor.class);

    @Autowired
    private RedisTokenLoader redisTokenLoader;
    @Autowired
    private TenantService tenantService;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate<Object, Object> redisTemplate;

    //网页安全授权URL
    @Value("${weChat.baseUrl}")
    private String baseUrl;

    //TOKEN格式
    private static final String REDIS_ACCESS_TOKEN_KEY_TEMP = "saas:{0}:access_token";

    /**
     * Controller之前执行
     * preHandle：拦截于请求刚进入时，进行判断，需要boolean返回值，如果返回true将继续执行，如果返回false，将不进行执行。一般用于登录校验
     * 1.当preHandle方法返回false时，从当前拦截器往回执行所有拦截器的afterCompletion方法，再退出拦截器链。也就是说，请求不继续往下传了，直接沿着来的链往回跑。
     * 2.当preHandle方法全为true时，执行下一个拦截器,直到所有拦截器执行完。再运行被拦截的Controller。然后进入拦截器链，运行所有拦截器的postHandle方法,完后从最后一个拦截器往回执行所有拦截器的afterCompletion方法.
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
        response.addHeader("Access-Control-Allow-Methods", "POST");
        response.addHeader("Access-Control-Max-Age", "1000");
        String osType = request.getHeader(HttpConstant.OS_TYPE);
        //获取微信服务器授权返回的code值
        String code = request.getParameter("code");
        HttpSession session = request.getSession();
        if (session.getAttribute(SessionConstants.SESSION_TENANT) != null) {
            return true;
        }
        //Tenant tenant = tenantService.selectByTenantCode("356451769");
        //session.setAttribute(SessionConstants.SESSION_TENANT, "356451769");
        session.setAttribute(SessionConstants.SESSION_TENANT, "MA4T4JPE8");

        return true;
    }

    /**
     * 返回信息给客户端
     *
     * @param response
     * @param out
     * @param tResponse
     */
    private void responseResult(HttpServletResponse response, PrintWriter out, TResponse tResponse) {
        response.setContentType(HttpConstant.CONTENT_TYPE_JSON);
        String json = JSONObject.toJSONString(tResponse);
        out.print(json);
        out.flush();
        out.close();
    }
}
